<?php

namespace app\admin\controller\system;

use app\admin\model\SystemApplication;
use app\admin\service\TriggerService;
use app\common\constants\AdminConstant;
use app\common\controller\AdminController;
use app\Request;
use think\App;
use think\db\exception\DbException;
use think\response\Json;

/**
 * Class Application
 * @package app\admin\controller\system
 * @ControllerAnnotation(title="应用管理")
 */
class Application extends AdminController
{

    protected array $sort = [
        'id'   => 'desc',
    ];

    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->model = new SystemApplication();
        $this->assign('auth_list', $this->model->getAuthList());
    }

    /**
     * @NodeAnnotation(title="列表")
     * @throws DbException
     */
    public function index(Request $request): Json|string
    {
        if ($request->isAjax()) {
            if (input('selectFields')) {
                return $this->selectList();
            }
            list($page, $limit, $where) = $this->buildTableParams();
            $count = $this->model
                ->where($where)
                ->count();
            $list  = $this->model
                ->where($where)
                ->page($page, $limit)
                ->order($this->sort)
                ->select()->toArray();
            $data  = [
                'code'  => 0,
                'msg'   => '',
                'count' => $count,
                'data'  => $list,
            ];
            return json($data);
        }
        return $this->fetch();
    }

    /**
     * @NodeAnnotation(title="添加")
     */
    public function add(Request $request): string
    {
        if ($request->isPost()) {
            $post             = $request->post();
            $authIds          = $request->post('auth_ids', []);

            $post['auth_ids'] = implode(',', array_keys($authIds));
            $rule             = [];
            $this->validate($post, $rule);
            try {
                $save = $this->model->save($post);
                $temptime = $this->model->getData('create_time');
                $token['auth_token'] = strtoupper(MD5($post['app_key'].$post['app_secret'].$temptime));
                $this->model->save($token);
            }catch (\Exception $e) {
                $this->error('保存失败');
            }
            $save ? $this->success('保存成功') : $this->error('保存失败');
        }
        return $this->fetch();
    }

    /**
     * @NodeAnnotation(title="编辑")
     */
    public function edit(Request $request, $id = 0): string
    {
        $row = $this->model->find($id);
        empty($row) && $this->error('数据不存在');
        if ($request->isPost()) {
            $post             = $request->post();
            $authIds          = $request->post('auth_ids', []);
            $post['auth_token'] = strtoupper(MD5($post['app_key'].$post['app_secret'].strtotime($row->create_time)));
            $post['auth_ids'] = implode(',', array_keys($authIds));
            $rule             = [];
            $this->validate($post, $rule);
            try {
                $save = $row->save($post);
                TriggerService::updateMenu($id);
            }catch (\Exception $e) {
                $this->error('保存失败');
            }
            $save ? $this->success('保存成功') : $this->error('保存失败');
        }
        $row->auth_ids = explode(',', $row->auth_ids ?: '');
        $this->assign('row', $row);
        return $this->fetch();
    }
    /**
     * @NodeAnnotation(title="查看")
     */
    public function view(Request $request, $id = 0): string
    {
        $row = $this->model->find($id);
        empty($row) && $this->error('数据不存在');
        $this->assign('row', $row);
        return $this->fetch();
    }
    /**
     * @NodeAnnotation(title="删除")
     */
    public function delete($id): void
    {
        $this->checkPostRequest();
        $row = $this->model->whereIn('id', $id)->select();
        $row->isEmpty() && $this->error('数据不存在');
        $id == AdminConstant::SUPER_ADMIN_ID && $this->error('超级管理员不允许修改');
        if (is_array($id)) {
            if (in_array(AdminConstant::SUPER_ADMIN_ID, $id)) {
                $this->error('超级管理员不允许修改');
            }
        }
        try {
            $save = $row->delete();
        }catch (\Exception $e) {
            $this->error('删除失败');
        }
        $save ? $this->success('删除成功') : $this->error('删除失败');
    }

    /**
     * @NodeAnnotation(title="属性修改")
     */
    public function modify(Request $request): void
    {
        $this->checkPostRequest();
        $post = $request->post();
        $rule = [
            'id|ID'      => 'require',
            'field|字段' => 'require',
            'value|值'   => 'require',
        ];
        $this->validate($post, $rule);
        if (!in_array($post['field'], $this->allowModifyFields)) {
            $this->error('该字段不允许修改：' . $post['field']);
        }
//        if ($post['id'] == AdminConstant::SUPER_ADMIN_ID && $post['field'] == 'status') {
//            $this->error('超级管理员状态不允许修改');
//        }
        $row = $this->model->find($post['id']);
        empty($row) && $this->error('数据不存在');
        try {
            $row->save([
                $post['field'] => $post['value'],
            ]);
        }catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success('保存成功');
    }


}
